package com.gjt.dlmall.product.exception;

import com.gjt.common.exception.DlmallEnum;
import com.gjt.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;

/**
 * Controller 统一异常处理
 * @author gjt
 * @version 1.0
 * @date 2021/9/10 0:53
 */
@RestControllerAdvice(basePackages = "com.gjt.dlmall.product。controller")
@Slf4j
public class DlmallExceptionControllerAdvice {

    //如果能够精确的匹配到该异常就会执行这个方法，后续执行下面的方法
    @ExceptionHandler(value = Exception.class)
    public R handleVaildException(MethodArgumentNotValidException e){
        //控制台打印
        log.error("数据效验出现问题{}，异常处理{}",e.getMessage(),e.getCause());
        //声明一个Map进行接收
        Map<String,String> map = new HashMap<>();

            //1、获取效验的错误结果
        BindingResult result = e.getBindingResult();
        result.getFieldErrors().forEach((fieldError)->{
            //获取每一个错误的属性名称
            String field = fieldError.getField();
            //获取每个错误提示
            String message = fieldError.getDefaultMessage();
            map.put(field,message);
        });
        // 调用枚举中的状态码 消息提示
        return R.error(DlmallEnum.VAILD_EXCEPTION.getCode(),DlmallEnum.VAILD_EXCEPTION.getMsg()).put("data",map);
    }
    @ExceptionHandler(value = Throwable.class)
    public R handleVaildException(Throwable throwable) {
        log.error("未知错误",throwable);
        return R.error(DlmallEnum.UNKNOW_EXCEPTION.getCode(),DlmallEnum.UNKNOW_EXCEPTION.getMsg()).put("data","未知异常");
    }
}
